package com.bjfu.educenter.controller;

import com.bjfu.common_utils.JwtUtils;
import com.bjfu.educenter.entity.UcenterMember;
import com.bjfu.educenter.service.UcenterMemberService;
import com.bjfu.educenter.utils.ConstantPropertiesUtil;
import com.bjfu.educenter.utils.HttpClientUtils;
import com.bjfu.servicebase.exceptionhandler.GuliException;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;

//@CrossOrigin
@Controller //只是请求地址不需要返回数据
@RequestMapping("/api/ucenter/wx")
public class WxApiController {
    @Autowired
    private UcenterMemberService memberService;
    // 1生成玩微信扫描二维码
    @GetMapping("login")
    public String getWxQRCode() {
       /* 拼接URL字符串，不要用这种方式
       String url = "https://open.weixin.qq.com/connect/qrconnect?appid=" +
                ConstantPropertiesUtil.WX_OPEN_APP_ID + "$response_type=";*/
        // 微信开发平台授权baseUrl,%s相当于占位符
        String baseUrl = "https://open.weixin.qq.com/connect/qrconnect" +
                "?appid=%s" +
                "&redirect_uri=%s" +
                "&response_type=code" +
                "&scope=snsapi_login" +
                "&state=%s" +
                "#wechat_redirect";

        // 对redirUrl进行URLEncoder编码
        String redirectUrl = ConstantPropertiesUtil.WX_OPEN_REDIRECT_URL;
        try {
            redirectUrl = URLEncoder.encode(redirectUrl, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            throw new GuliException(20001, e.getMessage());
        }

        //设置%s的值
        String qrcodeUrl = String.format(
                baseUrl,
                ConstantPropertiesUtil.WX_OPEN_APP_ID,
                redirectUrl,
                "atguigu");

        // 重定向到请求微信地址
        return "redirect:" + qrcodeUrl;
    }

    // 2 获取扫描人信息，添加数据
    @GetMapping("callback")
    public String callback(String code, String state) {
        System.out.println(code);
        System.out.println(state);
        //  1.获取code值，临时票据，类似于验证码

        // 2.拿着code请求微信固定的地址，得到两个值 access_token
        String baseAccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token" +
                "?appid=%s" +
                "&secret=%s" +
                "&code=%s" +
                "&grant_type=authorization_code";
        //拼接三个参数：id、秘钥、code值
        String accessTokenUrl = String.format(
                baseAccessTokenUrl,
                ConstantPropertiesUtil.WX_OPEN_APP_ID,
                ConstantPropertiesUtil.WX_OPEN_APP_SECRET,
                code);
        // 请求这个拼接好的地址，得到范湖两个值 access_token和openid
        // 使用httpclient发送请求，得到返回结果
        String accessTokenInfo = null;
        try {
            accessTokenInfo = HttpClientUtils.get(accessTokenUrl);
            System.out.println("accessTokenInfo:" + accessTokenInfo);
        } catch (Exception e) {
            e.printStackTrace();
            throw new GuliException(20001, "获取access_token失败");
        }

        // parsing String(json) to Map like
        Gson gson = new Gson();
        HashMap<String, Object> accessMap = gson.fromJson(accessTokenInfo, HashMap.class);
        String access_token = (String) accessMap.get("access_token");
        String openid = (String) accessMap.get("openid");


        String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                "?access_token=%s" +
                "&openid=%s";
        baseUserInfoUrl = String.format(
                baseUserInfoUrl,
                access_token,
                openid
        );
        // find member by openid
        UcenterMember member = memberService.getMemberByOpenId(openid);

        if (member == null) {
            String userInfo = null;
            try {
                userInfo = HttpClientUtils.get(baseUserInfoUrl);
                System.out.println(userInfo);
            }catch (Exception e){
                e.printStackTrace();
                throw new GuliException(20001,"get baseUserInfo failed");
            }
            gson = new Gson();
            HashMap userMap = gson.fromJson(userInfo, HashMap.class);
            String nickName = (String) userMap.get("nickname");
            String avatar = (String) userMap.get("headimgurl");
            Integer sex = ((Double) userMap.get("sex")).intValue();

            // create current User Information
            member= new UcenterMember();
            member.setOpenid(openid);
            member.setNickname(nickName);
            member.setAvatar(avatar);
            member.setSex(Integer.valueOf(sex));
            // check it has been existed user ?
            memberService.save(member);
        }

        // use jwt generate a token
        String jwtToken = JwtUtils.getJwtToken(member.getId(), member.getNickname());

        //finally, return First Page take token
        return "redirect:http://localhost:3000?token=" + jwtToken;
    }
}
